package com.example.ziliao.ui.years

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.example.ziliao.R
import com.example.ziliao.databinding.FragmentYearsBinding
import com.example.ziliao.utils.ViewHelper
import kotlin.random.Random

class YearsFragment : Fragment() {
    private var _binding: FragmentYearsBinding? = null
    private val binding get() = _binding!!

    private lateinit var buttonStart: Button
    private lateinit var optionsContainer: View
    private lateinit var resultText: TextView
    private lateinit var labelA: TextView
    private lateinit var labelB: TextView
    private lateinit var questionText: TextView
    private lateinit var btnOptionA: Button
    private lateinit var btnOptionB: Button
    private lateinit var btnOptionC: Button
    private lateinit var btnOptionD: Button
    private lateinit var btnOptionE: Button

    private val valueAViews = mutableListOf<TextView>()
    private val valueBViews = mutableListOf<TextView>()

    private val set1 = listOf(
        "面积" to "产量",
        "人" to "面积",
        "人" to "产量",
        "亩" to "人"
    )

    private val set2 = listOf(
        "产量" to "面积",
        "面积" to "人",
        "产量" to "人",
        "人" to "亩"
    )

    private val ratioToQuestion = mapOf(
        "面积" to "产量" to "单位面积产量",
        "产量" to "面积" to "单位面积产量",
        "人" to "面积" to "单位面积人数",
        "面积" to "人" to "单位面积人数",
        "人" to "产量" to "人均产量",
        "产量" to "人" to "人均产量",
        "亩" to "人" to "平均每亩人数",
        "人" to "亩" to "平均每亩人数"
    )

    private val questionTemplate1 = "列表中，{}同比增长的年份有多少个？"
    private val questionTemplate2Highest = "求这五年里{}最高的年份"
    private val questionTemplate2Lowest = "求这五年里{}最低的年份"
    private val questionTemplate3 = "{}{}的变化趋势"
    private val questionTemplate4 = "2022-2025年{}的同比增量排序"

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentYearsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        buttonStart = binding.buttonStart
        optionsContainer = binding.optionsContainer
        resultText = binding.resultText
        labelA = binding.labelA
        labelB = binding.labelB
        questionText = binding.questionText
        btnOptionA = binding.optionA
        btnOptionB = binding.optionB
        btnOptionC = binding.optionC
        btnOptionD = binding.optionD
        btnOptionE = binding.optionE

        // 初始化数值视图
        valueAViews.addAll(listOf(
            binding.valueA1,
            binding.valueA2,
            binding.valueA3,
            binding.valueA4,
            binding.valueA5
        ))

        valueBViews.addAll(listOf(
            binding.valueB1,
            binding.valueB2,
            binding.valueB3,
            binding.valueB4,
            binding.valueB5
        ))

        buttonStart.setOnClickListener {
            resetOptions()
            generateNumbers()
        }
    }

    private fun generateNumbers() {
        val numbersA = generateRandomNumbers()
        val numbersB = generateRandomNumbers()
        
        // 随机选择集合和关系
        val useSet1 = Random.nextBoolean()
        val selectedSet = if (useSet1) set1 else set2
        val selectedPair = selectedSet.random()
        
        // 设置标签
        labelA.text = selectedPair.first
        labelB.text = selectedPair.second

        // 随机选择题型
        val questionType = Random.nextInt(1, 5)
        val ratioText = ratioToQuestion[selectedPair] ?: ""

        when (questionType) {
            1 -> {
                // 第一种题型：同比增长的年份
                questionText.text = questionTemplate1.replace("{}", ratioText)
                generateType1(numbersA, numbersB, useSet1)
            }
            2 -> {
                // 第二种题型：最高/最低的年份
                val isHighest = Random.nextBoolean()
                questionText.text = if (isHighest) {
                    questionTemplate2Highest.replace("{}", ratioText)
                } else {
                    questionTemplate2Lowest.replace("{}", ratioText)
                }
                generateType2(numbersA, numbersB, useSet1, isHighest)
            }
            3 -> {
                // 第三种题型：连续三年趋势
                val use2022To2024 = Random.nextBoolean()
                val yearRange = if (use2022To2024) "2022-2024" else "2023-2025"
                questionText.text = questionTemplate3
                    .replaceFirst("{}", yearRange)
                    .replaceFirst("{}", ratioText)
                generateType3(numbersA, numbersB, useSet1, use2022To2024)
            }
            4 -> {
                // 第四种题型：同比增量排序
                questionText.text = questionTemplate4.replace("{}", ratioText)
                generateType4(numbersA, numbersB, useSet1)
            }
        }
    }

    // 计算商值的公共方法
    private fun calculateRatios(numbersA: List<Double>, numbersB: List<Double>, useSet1: Boolean): List<Double> {
        return if (useSet1) {
            numbersB.zip(numbersA).map { (b, a) -> b / a }
        } else {
            numbersA.zip(numbersB).map { (a, b) -> a / b }
        }
    }

    private fun generateType1(numbersA: List<Double>, numbersB: List<Double>, useSet1: Boolean) {
        // 设置选项文本
        btnOptionA.text = "A.0个"
        btnOptionB.text = "B.1个"
        btnOptionC.text = "C.2个"
        btnOptionD.text = "D.3个"
        btnOptionE.text = "E.4个"

        // 显示数值
        numbersA.forEachIndexed { index, number ->
            valueAViews[index].text = when {
                number < 1000 -> String.format("%.1f", number)
                number < 10000 -> number.toInt().toString()
                number < 100000 -> number.toInt().toString()
                else -> number.toInt().toString()
            }
        }

        // 如果是人数，生成整数
        numbersB.forEachIndexed { index, number ->
            valueBViews[index].text = if (labelA.text == "人" || labelB.text == "人") {
                number.toInt().toString()
            } else {
                when {
                    number < 1000 -> String.format("%.1f", number)
                    number < 10000 -> number.toInt().toString()
                    number < 100000 -> number.toInt().toString()
                    else -> number.toInt().toString()
                }
            }
        }

        // 计算比值并找出同比增长的年份
        val ratios = calculateRatios(numbersA, numbersB, useSet1)
        val growthYears = mutableListOf<Int>()
        for (i in 1 until ratios.size) {
            if (ratios[i] > ratios[i - 1]) {
                growthYears.add(i + 2021)
            }
        }

        // 显示所有组件
        binding.tableLayout.visibility = View.VISIBLE
        binding.questionText.visibility = View.VISIBLE
        binding.optionsContainer.visibility = View.VISIBLE

        val correctAnswer = growthYears.size
        btnOptionA.setOnClickListener { handleOptionClick(0, correctAnswer, growthYears) }
        btnOptionB.setOnClickListener { handleOptionClick(1, correctAnswer, growthYears) }
        btnOptionC.setOnClickListener { handleOptionClick(2, correctAnswer, growthYears) }
        btnOptionD.setOnClickListener { handleOptionClick(3, correctAnswer, growthYears) }
        btnOptionE.setOnClickListener { handleOptionClick(4, correctAnswer, growthYears) }
    }

    private fun generateType2(numbersA: List<Double>, numbersB: List<Double>, useSet1: Boolean, isHighest: Boolean) {
        // 设置选项文本
        btnOptionA.text = "A.2021年"
        btnOptionB.text = "B.2022年"
        btnOptionC.text = "C.2023年"
        btnOptionD.text = "D.2024年"
        btnOptionE.text = "E.2025年"

        // 显示第一行数值
        numbersA.forEachIndexed { index, number ->
            valueAViews[index].text = when {
                number < 1000 -> String.format("%.1f", number)
                number < 10000 -> number.toInt().toString()
                number < 100000 -> number.toInt().toString()
                else -> number.toInt().toString()
            }
        }

        // 生成第二行数值，确保商不重复
        val ratios = mutableListOf<Double>()
        val newNumbersB = mutableListOf<Double>()
        
        // 生成第一个数
        var lastNumber = if (labelA.text == "人" || labelB.text == "人") {
            Random.nextDouble(300.0, 500.0).toInt().toDouble()
        } else {
            Random.nextDouble(300.0, 500.0)
        }
        newNumbersB.add(lastNumber)
        
        // 计算第一个商
        val firstRatio = if (useSet1) {
            lastNumber / numbersA[0]
        } else {
            numbersA[0] / lastNumber
        }
        ratios.add(firstRatio)

        // 生成后续的数，确保商不重复
        for (i in 1 until 5) {
            var newNumber: Double
            var newRatio: Double
            do {
                val min = lastNumber * 0.6
                val max = lastNumber * 1.4
                newNumber = if (labelA.text == "人" || labelB.text == "人") {
                    Random.nextDouble(min, max).toInt().toDouble()
                } else {
                    Random.nextDouble(min, max)
                }
                newRatio = if (useSet1) {
                    newNumber / numbersA[i]
                } else {
                    numbersA[i] / newNumber
                }
            } while (ratios.contains(newRatio))
            
            newNumbersB.add(newNumber)
            ratios.add(newRatio)
            lastNumber = newNumber
        }

        // 显示第二行数值
        newNumbersB.forEachIndexed { index, number ->
            valueBViews[index].text = if (labelA.text == "人" || labelB.text == "人") {
                number.toInt().toString()
            } else {
                when {
                    number < 1000 -> String.format("%.1f", number)
                    number < 10000 -> number.toInt().toString()
                    number < 100000 -> number.toInt().toString()
                    else -> number.toInt().toString()
                }
            }
        }

        // 找出最高/最低的年份
        val extremeIndex = if (isHighest) {
            ratios.indexOf(ratios.maxOrNull())
        } else {
            ratios.indexOf(ratios.minOrNull())
        }

        // 显示所有组件
        binding.tableLayout.visibility = View.VISIBLE
        binding.questionText.visibility = View.VISIBLE
        binding.optionsContainer.visibility = View.VISIBLE

        // 设置点击事件，传入最高/最低的年份索引
        btnOptionA.setOnClickListener { handleOptionClick(0, extremeIndex) }
        btnOptionB.setOnClickListener { handleOptionClick(1, extremeIndex) }
        btnOptionC.setOnClickListener { handleOptionClick(2, extremeIndex) }
        btnOptionD.setOnClickListener { handleOptionClick(3, extremeIndex) }
        btnOptionE.setOnClickListener { handleOptionClick(4, extremeIndex) }
    }

    private fun generateType3(numbersA: List<Double>, numbersB: List<Double>, useSet1: Boolean, use2022To2024: Boolean) {
        // 设置选项文本
        btnOptionA.text = "A.连续上升"
        btnOptionB.text = "B.连续下降"
        btnOptionC.text = "C.先升后降"
        btnOptionD.text = "D.先降后升"
        btnOptionE.visibility = View.GONE

        // 显示数值
        numbersA.forEachIndexed { index, number ->
            valueAViews[index].text = when {
                number < 1000 -> String.format("%.1f", number)
                number < 10000 -> number.toInt().toString()
                number < 100000 -> number.toInt().toString()
                else -> number.toInt().toString()
            }
        }

        // 如果是人数，生成整数
        numbersB.forEachIndexed { index, number ->
            valueBViews[index].text = if (labelA.text == "人" || labelB.text == "人") {
                number.toInt().toString()
            } else {
                when {
                    number < 1000 -> String.format("%.1f", number)
                    number < 10000 -> number.toInt().toString()
                    number < 100000 -> number.toInt().toString()
                    else -> number.toInt().toString()
                }
            }
        }

        // 计算比值
        val ratios = calculateRatios(numbersA, numbersB, useSet1)
        
        // 根据年份范围选择要比较的三个商值
        val startIndex = if (use2022To2024) 1 else 2
        val threeRatios = ratios.subList(startIndex, startIndex + 3)
        
        // 判断趋势
        val correctAnswer = when {
            threeRatios[0] < threeRatios[1] && threeRatios[1] < threeRatios[2] -> 0 // 连续上升
            threeRatios[0] > threeRatios[1] && threeRatios[1] > threeRatios[2] -> 1 // 连续下降
            threeRatios[0] < threeRatios[1] && threeRatios[1] > threeRatios[2] -> 2 // 先升后降
            threeRatios[0] > threeRatios[1] && threeRatios[1] < threeRatios[2] -> 3 // 先降后升
            else -> 0
        }

        // 显示所有组件
        binding.tableLayout.visibility = View.VISIBLE
        binding.questionText.visibility = View.VISIBLE
        binding.optionsContainer.visibility = View.VISIBLE

        // 设置点击事件
        btnOptionA.setOnClickListener { handleOptionClick(0, correctAnswer) }
        btnOptionB.setOnClickListener { handleOptionClick(1, correctAnswer) }
        btnOptionC.setOnClickListener { handleOptionClick(2, correctAnswer) }
        btnOptionD.setOnClickListener { handleOptionClick(3, correctAnswer) }
    }

    private fun generateType4(numbersA: List<Double>, numbersB: List<Double>, useSet1: Boolean) {
        // 设置选项文本
        btnOptionE.visibility = View.GONE

        // 显示数值
        numbersA.forEachIndexed { index, number ->
            valueAViews[index].text = when {
                number < 1000 -> String.format("%.1f", number)
                number < 10000 -> number.toInt().toString()
                number < 100000 -> number.toInt().toString()
                else -> number.toInt().toString()
            }
        }

        // 如果是人数，生成整数
        numbersB.forEachIndexed { index, number ->
            valueBViews[index].text = if (labelA.text == "人" || labelB.text == "人") {
                number.toInt().toString()
            } else {
                when {
                    number < 1000 -> String.format("%.1f", number)
                    number < 10000 -> number.toInt().toString()
                    number < 100000 -> number.toInt().toString()
                    else -> number.toInt().toString()
                }
            }
        }

        // 计算比值
        val ratios = calculateRatios(numbersA, numbersB, useSet1)
        
        // 计算同比增量
        val increments = mutableListOf<Pair<Int, Double>>()
        for (i in 1 until ratios.size) {
            increments.add(i + 2021 to (ratios[i] - ratios[i - 1]))
        }
        
        // 按增量排序
        val sortedIncrements = increments.sortedByDescending { it.second }
        
        // 生成正确选项
        val isAscending = Random.nextBoolean()
        val correctOrder = if (isAscending) {
            sortedIncrements.reversed()
        } else {
            sortedIncrements
        }
        
        // 生成迷惑选项
        val wrongOptions = generateWrongOptions(correctOrder)
        
        // 设置选项文本
        val options = listOf(
            correctOrder,
            wrongOptions[0],
            wrongOptions[1],
            wrongOptions[2]
        )
        
        // 随机打乱选项顺序
        val shuffledOptions = options.shuffled()
        val correctIndex = shuffledOptions.indexOf(correctOrder)
        
        // 更新按钮文本
        btnOptionA.text = "A.${formatOptionText(shuffledOptions[0])}"
        btnOptionB.text = "B.${formatOptionText(shuffledOptions[1])}"
        btnOptionC.text = "C.${formatOptionText(shuffledOptions[2])}"
        btnOptionD.text = "D.${formatOptionText(shuffledOptions[3])}"

        // 显示所有组件
        binding.tableLayout.visibility = View.VISIBLE
        binding.questionText.visibility = View.VISIBLE
        binding.optionsContainer.visibility = View.VISIBLE

        // 设置点击事件
        btnOptionA.setOnClickListener { handleOptionClick(0, correctIndex) }
        btnOptionB.setOnClickListener { handleOptionClick(1, correctIndex) }
        btnOptionC.setOnClickListener { handleOptionClick(2, correctIndex) }
        btnOptionD.setOnClickListener { handleOptionClick(3, correctIndex) }
    }

    private fun generateWrongOptions(correctOrder: List<Pair<Int, Double>>): List<List<Pair<Int, Double>>> {
        val wrongOptions = mutableListOf<List<Pair<Int, Double>>>()
        val wrongPatterns = listOf(
            listOf(0, 1, 3, 2), // abdc
            listOf(0, 2, 1, 3), // acbd
            listOf(0, 2, 3, 1), // acdb
            listOf(1, 0, 2, 3), // bacd
            listOf(1, 0, 3, 2), // badc
            listOf(1, 2, 0, 3), // bcad
            listOf(2, 0, 1, 3), // cabd
            listOf(2, 0, 3, 1)  // cadb
        )
        
        // 随机选择3个不同的模式
        val selectedPatterns = wrongPatterns.shuffled().take(3)
        
        selectedPatterns.forEach { pattern ->
            val wrongOption = pattern.map { correctOrder[it] }
            wrongOptions.add(wrongOption)
        }
        
        return wrongOptions
    }

    private fun formatOptionText(order: List<Pair<Int, Double>>): String {
        return order.joinToString(">") { "${it.first}年" }
    }

    private fun generateRandomNumbers(): List<Double> {
        val numbers = mutableListOf<Double>()
        var lastNumber = Random.nextDouble(300.0, 500.0)
        numbers.add(lastNumber)

        repeat(4) {
            val min = lastNumber * 0.6
            val max = lastNumber * 1.4
            lastNumber = Random.nextDouble(min, max)
            numbers.add(lastNumber)
        }

        return numbers
    }

    private fun handleOptionClick(selectedIndex: Int, correctAnswer: Int, growthYears: List<Int>? = null) {
        // 使用ViewHelper处理点击事件
        ViewHelper.handleOptionClick(
            selectedIndex,
            correctAnswer,
            btnOptionA,
            btnOptionB,
            btnOptionC,
            btnOptionD,
            btnOptionE
        )

        // 显示结果
        resultText.text = if (growthYears != null) {
            "${growthYears.joinToString("年、")}年"
        } else if (btnOptionA.text.toString().startsWith("A.连续上升")) {
            // 第三种题型不显示结果
            ""
        } else if (btnOptionA.text.toString().contains("年>")) {
            // 第四种题型：显示同比增量
            val ratios = calculateRatios(
                valueAViews.map { it.text.toString().toDouble() },
                valueBViews.map { it.text.toString().toDouble() },
                set1.contains(labelA.text to labelB.text)
            )
            val increments = mutableListOf<Double>()
            for (i in 1 until ratios.size) {
                increments.add(ratios[i] - ratios[i - 1])
            }
            increments.joinToString("、") { String.format("%.2f", it) }
        } else {
            val ratios = calculateRatios(
                valueAViews.map { it.text.toString().toDouble() },
                valueBViews.map { it.text.toString().toDouble() },
                set1.contains(labelA.text to labelB.text)
            )
            val ratio = ratios[correctAnswer]
            "${2021 + correctAnswer}年，${String.format("%.2f", ratio)}"
        }
        resultText.visibility = View.VISIBLE
    }

    private fun resetOptions() {
        // 隐藏所有组件
        binding.tableLayout.visibility = View.GONE
        binding.questionText.visibility = View.GONE
        binding.optionsContainer.visibility = View.GONE
        
        // 重置按钮状态
        ViewHelper.resetButtonState(
            btnOptionA,
            btnOptionB,
            btnOptionC,
            btnOptionD,
            btnOptionE
        )
        
        // 重置结果文本
        ViewHelper.resetResultText(resultText)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 